﻿using Ivony.Html;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;


namespace DownLoadUNPKG
{
    class Program
    {
        static Ivony.Html.Parser.JumonyParser jumony;
        static IHtmlDocument doc;
        //static string url = "https://unpkg.com/browse/element-ui@2.13.0/";
        static string url = "";

        static WebClient web = new WebClient();

        static string baseDir = Environment.CurrentDirectory + "\\Data\\";


        static List<string> list = new List<string>();

        static void Main(string[] args)
        {
            jumony = new Ivony.Html.Parser.JumonyParser();
            web.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36");

            Console.WriteLine("说明：");
            Console.WriteLine("例如：https://unpkg.com/browse/element-ui@2.13.0/");
            Console.WriteLine("输出文件保存在根目录Data中：");
            Console.WriteLine("请输入地址：");
            url = Console.ReadLine();

            readFile(url, baseDir);
            Console.WriteLine("下载完成");
            Console.ReadKey();
        }

        static void readFile(string myUrl, string fileAddress)
        {
         
            byte[] downData;
            try
            {
                downData = web.DownloadData(myUrl);
            }
            catch
            {
                return;
            }
            string html = Encoding.UTF8.GetString(downData);
            doc = new Ivony.Html.Parser.JumonyParser().Parse(html);
            var tds = doc.Find("td a");
            foreach (var item in tds)
            {
                var value = item.Attribute("href").Value();
                if (value == "../")
                    continue;
                var dd = myUrl + value;
                list.Add(dd);
                Console.WriteLine(dd);
                string endValue = value.Substring(value.Length - 1, 1);
                if (endValue == "/")
                {
                    string address = fileAddress + value.TrimEnd('/') + "\\";
                    if (!Directory.Exists(address))//如果不存在就创建 dir 文件夹  
                        Directory.CreateDirectory(address);
                    
                    readFile(dd, address);
                }
                else
                {
                    string address = fileAddress + value;
                    try
                    {
                        web.DownloadFile(dd, address);
                    }
                    catch 
                    {
                    }
                    
                }
            }
        }

    }
}
